package org.umss.fixture.activities;

import org.umss.fixture.R;
import org.umss.fixture.services.FixtureBuilderServices;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class GameResultActivity extends Activity {
    private static ProgressDialog progressDialog;
    private String gameId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game_result);

        progressDialog = new ProgressDialog(this);
        final Button button = (Button) findViewById(R.id.saveScores);
        Bundle bundle = getIntent().getExtras();
        gameId = bundle.getString("GAME_ID");
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                TextView localScoreResult = (TextView) findViewById(R.id.localScoreResult);
                TextView visitorScoreResult = (TextView) findViewById(R.id.visitorScoreResult);

                new SaveGameResults().execute(gameId, localScoreResult.getText().toString(),
                        visitorScoreResult.getText().toString());
            }
        });
    }

    private class SaveGameResults extends AsyncTask<String, Void, Void> {

        @Override
        public void onPreExecute() {
            if (progressDialog != null) {
                progressDialog.setIndeterminate(true);
                progressDialog.setCancelable(false);
                progressDialog.setMessage("Saving championship...");
                progressDialog.show();
            }
        }

        @Override
        protected Void doInBackground(String... params) {
            String id = params[0];
            int localScore = Integer.parseInt(params[1]);
            int visitorScore = Integer.parseInt(params[2]);
            FixtureBuilderServices services = new FixtureBuilderServices();
            services.saveResult(id, localScore, visitorScore);
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            finish();
            if (progressDialog != null) {
                progressDialog.dismiss();
            }

            progressDialog = null;
        }
    }

}
